package com.bier.fishproject.activity;

import java.util.Timer;
import java.util.TimerTask;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.json.JSONObject;
import com.bier.fishproject.R;
import com.bier.fishproject.utils.Base64Str;
import com.bier.fishproject.utils.Constant;
import com.bier.fishproject.utils.MyThreadPool;
import com.bier.fishproject.utils.Shared;
import com.bier.fishproject.utils.YLWWater;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
/**
 * 登录
 * @author Administrator
 *
 */
public class LoginActivity extends BaseActivity implements OnClickListener{

	private EditText etCode,etPwd;
	private TextView tvCode,tvHead,tvLogin;
	private Timer mTimer=null;
	private int TIMENUM=60;
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login);
		initView();
	}
	
	/**
	 * 初始化控件
	 */
	private void initView(){
		etCode=(EditText)findViewById(R.id.et_al_code);
		etPwd=(EditText)findViewById(R.id.et_al_pwd);
		tvHead=(TextView)findViewById(R.id.tv_head);
		tvLogin=(TextView)findViewById(R.id.tv_login);
		tvHead.setText(R.string.app_name);
		tvCode=(TextView)findViewById(R.id.tv_al_getcode);
		etCode.setInputType(EditorInfo.TYPE_CLASS_PHONE); 
		etPwd.setInputType(EditorInfo.TYPE_CLASS_PHONE); 
		etCode.setText(Shared.readString(getApplicationContext(), "code"));
		if(etCode.getText().toString().length()==5){
			tvCode.setClickable(true);
			tvCode.setOnClickListener(LoginActivity.this);
			tvCode.setTextColor(getResources().getColor(R.color.main_color));
		}
		etCode.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}
			public void beforeTextChanged(CharSequence s, int start, int count,int after) {
			}
			@SuppressLint("ResourceAsColor") public void afterTextChanged(Editable s) {
				if(s.toString().length()==5){
					tvCode.setClickable(true);
					tvCode.setOnClickListener(LoginActivity.this);
					tvCode.setTextColor(getResources().getColor(R.color.main_color));
				}else{
					tvCode.setClickable(false);
					tvCode.setTextColor(getResources().getColor(R.color.main_colors));
				}
			}
		});
		etPwd.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}
			public void beforeTextChanged(CharSequence s, int start, int count,int after) {
			}
			@SuppressLint({ "ResourceAsColor", "NewApi" }) public void afterTextChanged(Editable s) {
				if(etCode.getText().toString().length()==5 && s.toString().length()==4){
					tvLogin.setClickable(true);
					tvLogin.setOnClickListener(LoginActivity.this);
					tvLogin.setBackground(getResources().getDrawable(R.drawable.login_textviews));
				}else{
					tvLogin.setClickable(false);
					tvLogin.setBackground(getResources().getDrawable(R.drawable.login_textview));
				}
			}
		});
	}


	public void onClick(View v) {
		switch(v.getId()){
		//获取验证码
		case R.id.tv_al_getcode:
			 loadView("正在获取验证码...");
			 MyThreadPool.getInstent().submit(new Runnable() {
				public void run() {
					try {
						TTransport transport = new TSocket(Constant.IP, Constant.PORT, 5000);
						transport.open();
						TProtocol protocol = new TBinaryProtocol(transport);
						TMultiplexedProtocol mp1 = new TMultiplexedProtocol(protocol, "YLWWater");
						YLWWater.Client client = new YLWWater.Client(mp1);
						String result=client.reqCode(etCode.getText().toString().trim());
						transport.close();
						if(!TextUtils.isEmpty(result)){
							final Message message=new Message();
							message.what=Constant.ONE;
							message.obj=result;
							handler.sendMessage(message);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			 });
			 break;
		//登录
		case R.id.tv_login:
			 loadView("正在登录...");
			 MyThreadPool.getInstent().submit(new Runnable() {
				public void run() {
					try {
						TTransport transport = new TSocket(Constant.IP, Constant.PORT, 5000);
						transport.open();
						TProtocol protocol = new TBinaryProtocol(transport);
						TMultiplexedProtocol mp1 = new TMultiplexedProtocol(protocol, "YLWWater");
						YLWWater.Client client = new YLWWater.Client(mp1);
						String result=client.doLogin(etCode.getText().toString().trim(),etPwd.getText().toString().trim(),1);
						transport.close();
						if(!TextUtils.isEmpty(result)){
							final Message message=new Message();
							message.what=Constant.FOUR;
							message.obj=result;
							handler.sendMessage(message);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			 });
			 break;
		default:
			 break;
		}
	}
	
	
	@SuppressLint("HandlerLeak") private Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			endView();
			switch(msg.what){
			//获取验证码返回
			case Constant.ONE:
				 try{
					String result=msg.obj.toString();
					final JSONObject json=new JSONObject(result);
					if(json.getInt("status")==0){
						showShortToast("验证码已发送！");
						mTimer = new Timer();
						 mTimer.scheduleAtFixedRate(new TimerTask() {
								public void run() {
									if(TIMENUM<=0){
										handler.sendEmptyMessage(Constant.THREE);
									}else{
										--TIMENUM;
										handler.sendEmptyMessage(Constant.TWO);
									}
								}
							}, 100, 1000);
					}else{
						showShortToast(json.getString("msg"));
					}
				 }catch(Exception e){
					e.printStackTrace();
				 }
				 break;
			case Constant.TWO:
				 tvCode.setText(TIMENUM+"秒");
				 break;
			case Constant.THREE:
				 mTimer.cancel(); 
				 TIMENUM=60;
				 tvCode.setText(R.string.get_pwd);
				 break;
			//登录返回
			case Constant.FOUR:
				 try{
					String result=msg.obj.toString();
					final JSONObject json=new JSONObject(result);
					if(json.getInt("status")==0){
						//保存卡号
						Shared.writeString(getApplicationContext(), "code", etCode.getText().toString().trim());
						Bundle bundle=new Bundle();
						bundle.putString("date", result);
						startActivity(MainActivity.class,bundle);
						LoginActivity.this.finish();
					}else{
						showShortToast(Base64Str.getFromBase64(json.getString("msg")));
					}
				 }catch(Exception e){
					e.printStackTrace();
				 }
				 break;
			default:
				 break;
			}
		};
	};
}
